/* global window */
import modelExtend from 'dva-model-extend'
import { config } from 'utils'
import { message } from 'antd'
import { getPushDataURLService, pushBatchDataService } from 'services/pushData'
import { pageModel } from 'utils/model'
import { number } from 'prop-types';

const { prefix } = config

export default modelExtend(pageModel, {
  namespace: 'pushData',

  state: {
    currentItem: {},
    modalVisible: false,
    modalType: 'create',
    selectedRowKeys: [],
    isMotion: window.localStorage.getItem(`${prefix}userIsMotion`) === 'true',
    editingKey: '',
    treeSelectData: [],
    listByOrganization: [],
    keywords: '',
    batchNumbers:[],
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/app/pushData') {
          dispatch({
            type: 'query',
            payload: location.query,
          })
        }
      })
    },
  },

  effects: {
    * query({ payload = {} }, { call, put }) {
      const data = yield call(getPushDataURLService, payload)
      if (data.success) {
        yield put({
          type: 'currentMethod',
          payload: {
            list: data.page.list,
            keywords: payload.keywords,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount,
            },
          },
        })
      }
    },
    *pushDataModals({ payload }, { call, put }) {
      const data = yield call(pushBatchDataService,{batchNumbers:payload.batchNumbers})
      if (data.success) {
        message.success('推送成功')
        yield put({type: 'query'})
      } else {
        message.error('推送失败')
      }
    },
    * changePage({ payload }, { call, put }) {
      const data = yield call(getPushDataURLService, { page: payload.page, pageSize: payload.pageSize, keywords: payload.keywords })
      if (data) {
        yield put({
          type: 'editingKey',
          payload: {
            list: data.page.list,
            keywords: payload.keywords,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount,
            },
          },
        })
      }
    },
    * queryKeyWords({ payload }, { call, put }) {
      const data = yield call(query, { ...payload })
      if (data) {
        yield put({
          type: 'editingKey',
          payload: {
            list: data.page.list,
            keywords: payload.keywords,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount,
            },
          },
        })
      }
    },
    * delete({ payload }, { call, put, select }) {
      const data = yield call(remove, { userIds: payload })
      const { selectedRowKeys } = yield select(_ => _.user)
      if (data.success) {
        yield put({ type: 'updateState', payload: { selectedRowKeys: selectedRowKeys.filter(_ => _ !== payload) } })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * multiDelete({ payload }, { call, put }) {
      const data = yield call(remove, payload)
      if (data.success) {
        yield put({ type: 'updateState', payload: { selectedRowKeys: [] } })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * create({ payload }, { call, put }) {
      const data = yield call(create, payload)
      if (data.success) {
        yield put({ type: 'hideModal' })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * update({ payload }, { select, call, put }) {
      const userId = yield select(({ user }) => user.currentItem.userId)
      const newUser = { ...payload, userId }
      const data = yield call(update, newUser)
      if (data.success) {
        yield put({ type: 'hideModal' })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * modal({ payload }, { call, put }) {
      let listByOrganization = []
      const roleData = yield call(roleList);
      listByOrganization = roleData.list
      const data = yield call(selection)
      if (payload.modalType === 'update') {
        const departmentData = yield call(departmentQuery, { orgId: payload.orgId });
        const rankData = yield call(rankQuery, { orgId: payload.orgId });
        if (data.success) {
          yield put({
            type: 'showModal',
            payload: {
              modalType: payload.modalType,
              treeSelectData: data.organizationList,
              currentItem: payload.modalType === 'update' ? payload.currentItem : '',
              listByOrganization,
              departmentList: departmentData.list,
              rankList: rankData.list,
            }
          })
        } else {
          throw data
        }
      } else {
        if (data.success) {
          yield put({
            type: 'showModal',
            payload: {
              modalType: payload.modalType,
              treeSelectData: data.organizationList,
              currentItem: payload.modalType === 'update' ? payload.currentItem : '',
              listByOrganization,
            }
          })
        } else {
          throw data
        }
      }

    },

    * roleList({ payload }, { call, put }) {
      const data = yield call(roleList, { organizationId: payload })
      const departmentData = yield call(departmentQuery, { orgId: payload });
      const rankData = yield call(rankQuery, { orgId: payload });
      if (data.success) {
        yield put({
          type: 'updateState',
          payload: {
            listByOrganization: data.list,
            departmentList: departmentData.list,
            rankList: rankData.list,
          }
        })
      } else {
        throw data
      }
    },
  },

  reducers: {
    currentMethod(state, { payload }) {
      return { ...state, ...payload, }
    },
    showModal(state, { payload }) {
      return { ...state, ...payload, modalVisible: true }
    },

    hideModal(state) {
      return { ...state, modalVisible: false }
    },

    switchIsMotion(state) {
      window.localStorage.setItem(`${prefix}userIsMotion`, !state.isMotion)
      return { ...state, isMotion: !state.isMotion }
    },

    editingKey(state, { payload }) {
      return { ...state, ...payload }
    }
  },
})
